<template>
	<yingbing-audio
	ref="audio"
	autoplay
	mode="background"
	:src="src"
	:poster="currentPoster"
	:title="currentTitle"
	:lyric="lyrics"
	:lyricConfig="lyricConfig"
	:shareConfig="shareConfig"
	@lyricChange="lyricChange"
	@ended="handleEnded"
	@canplay="handleCanplay"
	@play="handlePlay"
	@pause="handlePause"
	@error="handleError"
	@timeUpdate="handleTimeUpdate"
	></yingbing-audio>
</template>
<script>
	import appMixin from '@/common/mixin/app.js'
	import NativeUI from '@/js_sdk/yb-native-ui/index.js'
	let ob = null
	let debug = null
	export default {
		mixins: [appMixin],
		computed: {
			lyricConfig () {
				return {
					mode: this.lyricShow ? 'overall' : 'hidden',
					fillColor: this.skinColor.color_theme_1,
					strokeColor: this.skinColor.color_1,
					offset: uni.getSystemInfoSync().windowBottom + uni.upx2px(20)
				}
			},
			shareConfig () {
				return {
					shareUrl: this.currentShareUrl,
					albumName: this.currentTitle || '',
					singer: this.currentCreator
				}
			},
			album () {
				return this.$store.getters['audio/getAlbum']
			},
			catalogId () {
				return this.$store.getters['audio/getCatalogId']
			},
			catalog () {
				const index = this.catalogs.findIndex(catalog => catalog.id == this.catalogId)
				return index > -1 ? this.catalogs[index] : null
			},
			currentCreator () {
				return this.catalog?.creator || this.creator || '未知歌手'
			},
			currentTitle () {
				return this.catalog?.title || this.album?.title
			},
			currentPoster () {
				return this.catalog?.cover || this.album?.cover || (this.catalogs && this.catalogs.length > 0 ? (this.catalogs[0].cover || '') : '')
			},
			currentShareUrl () {
				return this.catalog?.shareUrl || this.album?.shareUrl || ''
			},
			lyrics () {
				return this.$store.getters['audio/getLyrics']
			},
			lyricShow () {
				return this.$store.getters['audio/getLyricShow']
			},
			catalogs () {
				return this.$store.getters['audio/getCatalogs']
			},
			parentCharacters () {
				return this.$store.getters['audio/getParentCharacters']
			},
			parentRecomes () {
				return this.$store.getters['audio/getParentRecomes']
			},
			randoms () {
				return this.$store.getters['audio/getRandoms']
			},
			debugger () {
				return this.$store.getters['app/getDebugger']
			}
		},
		data () {
			return {
				src: '',
				loading: false
			}
		},
		beforeCreate() {
			uni.$on('debug', data => {
				debug && debug.show()
			})
			uni.$on('scircle', data => {
				ob.show()
			})
			uni.$on('goPlayer', data => {
				ob.hide()
				getApp().globalData.$Router.push({
					path: '/pages/audio/player',
					animationType: 'fade-in',
					query: { params: encodeURIComponent(JSON.stringify(this.album)) }
				})
			})
			uni.$on('seekSong', time => {
				this.seek(time)
			})
			uni.$on('play', () => {
				this.play()
			})
			uni.$on('pause', () => {
				this.pause()
			})
		},
		beforeDestroy () {
			ob.close()
			ob = null
			this.$store.dispatch('audio/destroy')
			debug && debug.close()
			debug = null
			uni.$off('debug')
			uni.$off('scircle')
			uni.$off('goPlayer')
			uni.$off('seekSong')
			uni.$off('play')
			uni.$off('pause')
			this.clearNextTimer()
		},
		created () {
			ob = NativeUI.scircle({
				width: uni.upx2px(60),
				height: uni.upx2px(60),
				left: this.windowWidth - 50,
				top: this.windowHeight - 60,
				border: 5,
				touch: true,
				dark: this.skinMode == 'night',
				func: (e) => {
					ob.hide()
					getApp().globalData.$Router.push({
						path: '/pages/audio/player',
						animationType: 'fade-in'
					})
				}
			})
			ob.show();
			if ( this.debugger ) {
				debug = NativeUI.scircle({
					width: uni.upx2px(200),
					height: uni.upx2px(80),
					left: uni.getSystemInfoSync().windowWidth - uni.upx2px(200),
					top: uni.getSystemInfoSync().windowHeight - uni.upx2px(200),
					border: 5,
					touch: true,
					text: '调试',
					dark: this.skinMode == 'night',
					func: (e) => {
						debug.hide()
						getApp().globalData.$Router.push({
							path: '/modules/debugger',
							animationType: 'slide-in-right'
						})
					}
				})
				debug.show();
			}
		},
		methods: {
			async getDetail () {
				return await this.$store.dispatch('network/request', {
					name: 'detail',
					url: this.catalog.detailUrl,
					source: this.album?.source,
					data: this.catalog
				})
			},
			async getRecome () {
				return await this.$store.dispatch('network/request', {
					name: 'recome',
					url: this.catalog.recomeUrl,
					source: this.album?.source,
					data: this.catalog
				})
			},
			async getCharacter () {
				return await this.$store.dispatch('network/request', {
					name: 'character',
					url: this.catalog.characterUrl,
					source: this.album?.source,
					data: this.catalog
				})
			},
			async getContext () {
				return await this.$store.dispatch('network/request', {
					name: 'context',
					url: this.catalog.contextUrl,
					source: this.album?.source,
					data: this.catalog
				})
			},
			async getLyric () {
				return await this.$store.dispatch('network/request', {
					name: 'lyric',
					url: this.catalog.lyricUrl,
					source: this.album?.source,
					data: this.catalog
				})
			},
			async handleStart () {
				this.clearNextTimer()
				this.loading = true
				if ( this.catalog.source != 'local' ) {
					const res1 = await this.getDetail()
					const data = res1.data?.data || {}
					const catalog = JSON.parse(JSON.stringify(this.catalog))
					Object.keys(data).forEach(key => {
						catalog[key] = data[key] || catalog[key]
					})
					const index = this.catalogs.findIndex(c => c.id == catalog.id)
					if ( index > -1 ) this.$set(this.catalogs, index, catalog)
					const res2 = await this.getContext()
					this.src = res2.data?.data?.src || this.catalog.src || ''
					this.loading = false
					if ( !this.src || this.catalog.isVip ) {
						uni.showToast({
							title: '付费资源，请支持正版，2秒后继续播放',
							icon: 'none',
							duration: 2000
						})
						this.nextTimer = setTimeout(() => {
							this.$store.dispatch('audio/next')
						}, 2000)
						return
					}
					const res3 = await this.getCharacter()
					this.$store.commit('audio/setCharacters', res3.data?.list || this.parentCharacters || [])
					const res4 = await this.getRecome()
					this.$store.commit('audio/setRecomes', res4.data?.list || this.parentRecomes || [])
					const res5 = await this.getLyric()
					const lyrics = res5.data?.list || []
					this.$store.commit('audio/setLyrics', lyrics.filter(lyric => lyric.title && lyric.time.toString() ))
				}
				if ( this.$store.getters['app/getHistory'] ) {
					this.$store.dispatch('resource/save', this.album)
					this.$store.dispatch('record/save', {
						id: this.album.id,
						catalogId: this.catalogId,
						title: this.catalog.title
					})
				}
			},
			getRandomPlayList () {
				let randomList = this.randoms.filter(rnd => this.catalogs.findIndex(ply => ply.id == rnd.id) > -1 )
				let otherList = this.catalogs.filter(rnd => this.randoms.findIndex(ply => ply.id == rnd.id) == -1 )
				let len = otherList.length
				let min = 0;
				let max = len - 1;
				let arr = [];
				while ( arr.length < len ) {
					let value = Math.floor(Math.random() * (max - min + 1)) + min;
					if ( arr.indexOf(value) == -1 ) {
						arr.push(otherList[value])
					}
				}
				return randomList.concat(arr)
			},
			lyricChange (e) {
				if ( this.loading ) return
				this.$store.commit('audio/setLyricIndex', e.index)
				this.$store.commit('audio/setLyricTitle', e.title)
			},
			handleCanplay (e) {
				if ( this.loading ) return
				this.$store.commit('audio/setDuration', e.duration)
			},
			handleTimeUpdate (e) {
				if ( this.loading ) return
				this.$store.commit('audio/setCurrentTime', e.currentTime)
			},
			handlePlay () {
				if ( this.loading ) return
				this.$store.commit('audio/setPaused', false)
			},
			handlePause () {
				if ( this.loading ) return
				this.$store.commit('audio/setPaused', true)
			},
			handleStop () {
				this.$store.dispatch('audio/stop')
			},
			handleEnded () {
				this.$store.dispatch('audio/next')
			},
			handleError () {
				uni.showToast({
					title: '播放失败，2秒后继续播放',
					icon: 'none',
					duration: 2000
				})
				this.nextTimer = setTimeout(() => {
					this.$store.dispatch('audio/next')
				}, 2000)
			},
			seek (time) {
				if ( this.loading ) return
				this.$refs.audio.seek(time)
			},
			play () {
				if ( this.loading ) return
				this.$refs.audio.play()
			},
			pause () {
				if ( this.loading ) return
				this.$refs.audio.pause()
			},
			stop () {
				if ( this.loading ) return
				this.$refs.audio.stop()
			},
			clearNextTimer () {
				if ( this.nextTimer ) {
					clearTimeout(this.nextTimer)
					this.nextTimer = null
				}
			}
		},
		watch: {
			catalogId (newVal, oldVal) {
				this.clearNextTimer()
				if ( newVal != oldVal && newVal ) {
					this.nextTimer = setTimeout(() => {
						this.handleStart()
					}, 500)
				} else { this.src = ''}
			},
			catalogs (newVal, oldVal) {
				this.$store.commit('audio/setRandoms', this.getRandomPlayList())
			},
			skinMode (newVal) {
				ob && ob.reset({
					dark: newVal == 'night'
				})
				debug && debug.reset({
					dark: newVal == 'night'
				})
			},
			debugger (newVal) {
				if ( newVal ) {
					debug = NativeUI.scircle({
						width: uni.upx2px(200),
						height: uni.upx2px(80),
						left: uni.getSystemInfoSync().windowWidth - uni.upx2px(200),
						top: uni.getSystemInfoSync().windowHeight - uni.upx2px(200),
						border: 5,
						touch: true,
						text: '调试',
						dark: this.skinMode == 'night',
						func: (e) => {
							debug.hide()
							getApp().globalData.$Router.push({
								path: '/modules/debugger',
								animationType: 'slide-in-right'
							})
						}
					})
					debug.show();
				} else {
					debug && debug.close()
					debug = null
				}
			}
		}
	}
</script>

<style>

</style>
